<template>
  <el-container>
    <el-header style="text-align: right; font-size: 12px">
      <el-row :gutter="20" style="display: flex;align-items: center;">
        <el-col :span="14">
          <el-page-header @back="goBack" :content="metadata.title" class="fontStyle"></el-page-header>
        </el-col>
        <el-col :span="10">
          <div class="header-right">
            <el-tooltip class="item" effect="dark" content="文献评级" placement="bottom-start">
              <el-button type="danger" icon="el-icon-sunny" circle plain @click="dialogRate=true"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="阅读记录" placement="bottom-start">
              <el-button type="warning" icon="el-icon-paperclip" circle plain
                         @click="readingProgressDrawer=true"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="标记与笔记" placement="bottom-start">
              <el-button type="success" icon="el-icon-message" circle plain @click="notesDrawer=true"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="文献信息" placement="bottom-start">
              <el-button type="info" icon="el-icon-info" circle plain @click="infoDrawer=true"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="目录" placement="bottom-start">
              <el-button type="primary" icon="el-icon-s-order" circle @click="drawer=true" plain></el-button>
            </el-tooltip>
          </div>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <div id="eBook" class="eBook" v-loading="!bookAvailable" element-loading-text="拼命加载中">
        <el-button round plain type="info" icon="el-icon-arrow-left" @click="prevPage">上一页</el-button>
        <div id="read"></div>
        <el-button round plain type="info" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i>
        </el-button>
      </div>
      <el-drawer
        :visible.sync="drawer"
        :size="size"
        :with-header="false"
        :direction="direction">
        <div class="content-item" v-for="(item, index) in navigation.toc" :key="index"
             @click="jumpTo(item.href)">
          <span class="text">{{ item.label }}</span>
        </div>
      </el-drawer>
      <el-drawer
        :visible.sync="infoDrawer"
        :size="size"
        :with-header="false"
        :direction="direction">
        <div style="padding: 20px">{{ metadata.title }}</div>
        <img style="width: 30%" :src="coverUrl" alt="">
        <el-descriptions style="padding: 20px" class="margin-top" :column="1" :size="size" border>
          <!--          <template slot="extra"><el-button type="primary" size="small">操作</el-button></template>-->
          <el-descriptions-item label="作者">{{ metadata.creator }}</el-descriptions-item>
          <el-descriptions-item label="语言">{{ metadata.language }}</el-descriptions-item>
          <el-descriptions-item label="文献编号">{{ bookInfoFromDataSource.numCode }}</el-descriptions-item>
          <el-descriptions-item label="文献种类">{{ bookType[bookInfoFromDataSource.type] }}</el-descriptions-item>
          <el-descriptions-item label="上传者编号">{{ bookInfoFromDataSource.uploadNum }}</el-descriptions-item>
          <el-descriptions-item label="上传者昵称">{{ bookInfoFromDataSource.username }}</el-descriptions-item>
          <el-descriptions-item label="出版社">{{ metadata.publisher }}</el-descriptions-item>
          <el-descriptions-item label="版权">{{ metadata.rights }}</el-descriptions-item>
        </el-descriptions>
      </el-drawer>
      <el-drawer
        title="我的笔记"
        :visible.sync="notesDrawer"
        direction="rtl"
        size="30%">
        <div>
          <el-button @click="notesInnerDrawer = true">查看其他读者的笔记!</el-button>
          <el-drawer
            title="其他读者的笔记"
            :append-to-body="true"
            :visible.sync="notesInnerDrawer">
            <div class="otherNotesStyle" v-for="(item, index) in otherNotes" :key="index">
              <el-badge :value="item.state===0?'私有':'公开'" class="item">
                <el-card class="box-card">
                  <el-row :gutter="20" style="display: flex; align-items: center;margin-bottom: 10px">
                    <el-col :span="5" style="text-align: left;">
                      <el-tag effect="plain" type="danger">标记</el-tag>
                    </el-col>
                    <el-col :span="19" style="text-align: left;font-size: 14px">{{ item.content }}</el-col>
                  </el-row>
                  <el-row :gutter="20" style="display: flex; align-items: center;">
                    <el-col :span="5" style="text-align: left;">
                      <el-tag effect="plain" type="success">笔记</el-tag>
                    </el-col>
                    <el-col :span="19" style="text-align: left;font-size: 14px">
                      {{ item.opinion === '' ? '暂无笔记' : item.opinion }}
                    </el-col>
                  </el-row>
                </el-card>
              </el-badge>
            </div>
            <div style="height: 80px"></div>
            <el-pagination
              background
              class="pageStyle"
              layout="prev, pager, next"
              @current-change="handleCurrentChangeOtherNote"
              :total="otherNotesCount">
            </el-pagination>
          </el-drawer>
        </div>
        <div v-for="(item, index) in notes" :key="index">
          <el-badge :value="item.state===0?'私有':'公开'" class="item">
            <el-card class="box-card">
              <div slot="header" class="clearfix" style="text-align: right">
                <el-button-group>
                  <el-button style="border: 0" @click="showNoteDialog(index)" size="small" type="default"
                             class="el-icon-edit"></el-button>
                  <el-popconfirm
                    title="这是一段内容确定删除吗？"
                    @confirm="confirmDelete(index)"
                  >
                    <el-button style="border: 0" slot="reference" size="small" type="default"
                               icon="el-icon-delete"></el-button>
                  </el-popconfirm>
                </el-button-group>
              </div>
              <el-row :gutter="20" style="display: flex; align-items: center;margin-bottom: 10px">
                <el-col :span="5" style="text-align: left;">
                  <el-tag effect="plain" type="danger">标记</el-tag>
                </el-col>
                <el-col :span="19" style="text-align: left;font-size: 14px">{{ item.content }}</el-col>
              </el-row>
              <el-row :gutter="20" style="display: flex; align-items: center;">
                <el-col :span="5" style="text-align: left;">
                  <el-tag effect="plain" type="success">笔记</el-tag>
                </el-col>
                <el-col :span="19" style="text-align: left;font-size: 14px">
                  {{ item.opinion === '' ? '暂无笔记' : item.opinion }}
                </el-col>
              </el-row>
            </el-card>
          </el-badge>
        </div>
        <div style="height: 80px"></div>
        <el-pagination
          background
          class="pageStyle"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :total="notesCount">
        </el-pagination>
      </el-drawer>
      <el-drawer
        title="阅读记录"
        :visible.sync="readingProgressDrawer"
        direction="btt">
        <el-slider style="width: 97%; margin: 0 auto" v-model="progressExtend" @change="handleSliderChange"></el-slider>
        <span>{{ progressExtend + '%' }}</span>
      </el-drawer>
      <el-dialog title="编辑笔记" :visible.sync="dialogFormVisible">
        <el-form label-width="80px">
          <el-form-item label="权限状态">
            <el-radio v-model="radio" label="0">私有</el-radio>
            <el-radio v-model="radio" label="1">共开</el-radio>
          </el-form-item>
          <el-form-item label="笔记">
            <el-input type="textarea"
                      :rows="10"
                      placeholder="请输入笔记"
                      v-model="dialogNotesUpdate" autocomplete="off">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false; updateNotes(noteIndex)">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogRate"
        width="30%">
        <div v-if="userReadingProgress.progress!==1">
          <span>您的阅读进度为</span>
          <span style="color: red"> {{ userReadingProgress.progress * 100 + '%' }}</span>
          <span>,阅读完之后才可以进行评价！</span>
        </div>
        <div v-if="userReadingProgress.progress===1">
          <el-rate v-model="rateValue"></el-rate>
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogRate = false">取 消</el-button>
    <el-button type="primary" @click="updateBookRate">确 定</el-button>
  </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>
<script>

import Epub from 'epubjs'
import {deleteRequest, getRequest, postRequest} from '../../tools/api'
import {mymessage} from '../../tools/mymessage'

export default {
  name: 'index',
  data () {
    return {
      rateValue: 0,
      dialogRate: false,
      notesInnerDrawer: false,
      readingProgressDrawer: false,
      drawer: false,
      infoDrawer: false,
      notesDrawer: false,
      direction: 'rtl',
      size: '400px',
      book: {},
      bookInfoFromDataSource: {},
      bookType: ['科技图书', '科技期刊', '专利文献', '科技报告', '政府出版物', '学位论文', '标准文献', '产品资料和', '其它文献'],
      coverUrl: '',
      rendition: {},
      navigation: {},
      bookAvailable: false,
      metadata: {},
      notes: [],
      otherNotes: [],
      notesPage: {
        page: 1,
        pageSize: 10
      },
      otherNotesPage: {
        page: 1,
        pageSize: 10
      },
      radio: 0,
      noteIndex: 0,
      dialogFormVisible: false,
      dialogNotesUpdate: '',
      selection: null,
      bookId: '',
      bookUrl: '',
      userReadingProgress: {progress: 0},
      notesCount: 10,
      otherNotesCount: 10,
      progressExtend: 0
    }
  },
  created () {
    this.bookId = this.$route.query.bookId
    this.bookUrl = this.$route.query.bookUrl
    this.initBookProgress()
    this.initBookInfoFromDataSource()
    this.initThisBookNotesByPage()
    this.initThisBookOtherNotesByPage()
    this.showEpub()
  },
  beforeDestroy () {
    this.updateDataSourceProgress()
  },
  methods: {
    updateBookRate () {
      if (this.userReadingProgress.progress === 1) {
        const rateDTO = {
          literatureId: this.bookId,
          userId: this.$store.getters.userInfo.id,
          grade: this.rateValue
        }
        postRequest('/rank/insert', rateDTO).then(res => {
          console.log('res')
          if (res.code === 200) {
            mymessage.success('评级成功！')
          }
        })
      }
      this.dialogRate = false
    },
    handleCurrentChange (val) {
      this.notesPage.page = val
      this.initThisBookNotesByPage()
    },
    handleCurrentChangeOtherNote (val) {
      this.otherNotesPage.page = val
      this.initThisBookOtherNotesByPage()
    },
    initBookInfoFromDataSource () {
      getRequest('/literaturedetail/queryLiteratureDetail/' + this.$store.getters.userInfo.id + '/' + this.bookId).then((res) => {
        if (res.code === 200) {
          this.bookInfoFromDataSource = res.data
          this.bookInfoFromDataSource.uploadNum = this.prefixInteger(this.bookInfoFromDataSource.uploadNum, 10)
        }
      })
    },
    prefixInteger (num, length) {
      return (Array(length).join('0') + num).slice(-length)
    },
    initBookProgress () {
      getRequest('/readingprogress/queryReadingProgress/' + this.$store.getters.userInfo.id + '/' + this.bookId).then(res => {
        if (res.code === 200) {
          if (res.data === undefined) { // 如果是首次阅读，添加阅读记录
            const progressInfo = {
              literatureId: this.bookId,
              userId: this.$store.getters.userInfo.id,
              progress: 0,
              fontSize: -1,
              theme: -1,
              typeface: -1,
              state: 0
            }
            postRequest('/readingprogress/insertReadingProgress', progressInfo).then(res => {
            })
            return
          } else {
            this.userReadingProgress = res.data
            this.progressExtend = Number((100 * this.userReadingProgress.progress).toFixed(2))
          }
          console.log('the progress of this book:', this.userReadingProgress.progress)
        }
      })
    },
    handleSliderChange (val) {
      const newProgress = Math.floor(val) / 100
      this.progressExtend = Number((val).toFixed(2))
      this.updateProgress(newProgress)
      this.displayProgress(newProgress)
    },
    updateProgress () {
      // 获得当前章节的百分比并设置 保留6位小数
      const currentLocation = this.book.rendition.currentLocation()
      this.userReadingProgress.progress = Number(currentLocation.end.percentage.toFixed(6))
      this.progressExtend = Number((this.userReadingProgress.progress * 100).toFixed(2))
      console.log('updateProgress:', this.userReadingProgress.progress)
    },
    displayProgress (progress) {
      this.userReadingProgress.progress = progress
      // 获得cfi地址 // progress的范围: 0-1
      const location = progress > 0 ? this.book.locations.cfiFromPercentage(progress) : 0
      // 根据cfi地址渲染电子书
      this.book.rendition.display(location)
    },
    initThisBookNotesByPage () {
      const checkInfoDTO = {
        literatureId: this.bookId,
        userId: this.$store.getters.userInfo.id,
        page: this.notesPage.page,
        pageSize: this.notesPage.pageSize
      }
      postRequest('/note/getNoteByPage', checkInfoDTO).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.notes = res.data.row.reverse()
          console.log('nots:', this.notes)
          this.notesCount = res.data.size
        }
      })
    },
    initThisBookOtherNotesByPage () {
      const checkInfoDTO = {
        literatureId: this.bookId,
        page: this.notesPage.page,
        pageSize: this.notesPage.pageSize,
        state: 1
      }
      postRequest('/note/getNoteByPage', checkInfoDTO).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.otherNotes = res.data.row.reverse()
          console.log('nots:', this.otherNotes)
          this.otherNotesCount = res.data.size
        }
      })
    },
    showNoteDialog (index) {
      this.noteIndex = index
      this.dialogFormVisible = true
      this.dialogNotesUpdate = this.notes[index].opinion
      this.radio = String(this.notes[index].state)
    },
    updateNotes (noteIndex) {
      this.notes[noteIndex].opinion = this.dialogNotesUpdate
      this.notes[noteIndex].state = this.radio
      const updateDTO = {
        id: this.notes[noteIndex].id,
        opinion: this.notes[noteIndex].opinion,
        state: Number(this.notes[noteIndex].state)
      }
      console.log('updateDTO:', updateDTO)
      postRequest('/note/updateNote', updateDTO).then(res => {
        if (res.code === 200) {
          mymessage.success('编辑成功！')
          this.initThisBookNotesByPage()
        }
      })
    },
    addNotes (text) {
      const notesInfo = {
        literatureId: this.bookId,
        userId: this.$store.getters.userInfo.id,
        state: 0,
        content: text,
        option: ''
      }
      postRequest('/note/insert', notesInfo).then(res => {
        if (res.code === 200) {
          this.$message.success('成功新增一条标记！')
          this.initThisBookNotesByPage()
        }
      })
    },
    confirmDelete (index) {
      deleteRequest('/note/deleteNote/' + this.notes[index].id + '/' + this.$store.getters.userInfo.id).then(res => {
        if (res.code === 200) {
          mymessage.success('删除成功！')
          this.initThisBookNotesByPage()
        }
      })
    },
    // 返回上一页（书架）
    goBack () {
      this.$router.go(-1)
    },
    // 根据链接跳转到指定位置
    jumpTo (href) {
      this.drawer = false
      this.rendition.display(href).then(() => {
        this.updateProgress()
      })
    },
    // 上一页
    prevPage () {
      if (this.rendition) {
        this.rendition.prev().then(() => {
          this.updateProgress()
        })
      }
    },
    // 下一页
    nextPage () {
      if (this.rendition) {
        this.rendition.next().then(() => {
          this.updateProgress()
        })
        // const location = percentage > 0 ? this.locations.cfiFromPercentage(percentage) : 0
        // this.rendition.display(location)
      }
    },
    showEpub () { // 电子书解析渲染
      this.book = new Epub(this.bookUrl) // 生成Book对象
      // 获取文献信息
      this.book.loaded.metadata.then(metadata => {
        this.metadata = metadata
      })
      // 获取封面信息
      this.book.loaded.cover.then(cover => {
        this.book.archive.createUrl(cover).then(url => {
          this.coverUrl = url
        })
      })
      // 通过Book.renderTo生成Rendition对象
      this.rendition = this.book.renderTo('read', {
        width: window.innerWidth - 460,
        height: window.innerHeight - 130,
        method: 'default'
      })
      // Illustration of how to get text from a saved cfiRange
      let that = this
      this.rendition.on('selected', function (cfiRange, contents) {
        this.book.getRange(cfiRange).then(function (range) {
          if (range) {
            const text = range.toString()
            that.addNotes(text)
          }
        })
      })
      // Apply a class to selected text
      this.rendition.themes.default({
        '::selection': {
          'background': 'rgba(255,255,0, 0.3)'
        },
        '.epubjs-hl': {
          'fill': 'yellow', 'fill-opacity': '0.3', 'mix-blend-mode': 'multiply'
        }
      })
      // Book对象的钩子函数ready
      this.book.ready.then(() => {
        this.navigation = this.book.navigation
        // 生成Locations对象
        return this.book.locations.generate()
      }).then(result => {
        // 保存locations对象
        this.locations = this.book.locations
        // 根据 progress 渲染电子书    // progress数值（0-1）小数
        this.displayProgress(this.userReadingProgress.progress)
        // 标记电子书为解析完毕状态
        this.bookAvailable = true
      })
    },
    updateDataSourceProgress () {
      const updateReadingProgress = {
        id: this.userReadingProgress.id,
        literatureId: this.bookId,
        userId: this.$store.getters.userInfo.id,
        progress: this.userReadingProgress.progress,
        fontSize: this.userReadingProgress.fontSize,
        theme: this.userReadingProgress.theme,
        typeface: this.userReadingProgress.typeface
      }
      postRequest('/readingprogress/queryReadingProgress', updateReadingProgress).then(res => {
        console.log('update Progress => res:', res)
      })
    }
  }
}
</script>

<style scoped>
.otherNotesStyle {
  display: flex;
  justify-content: center;
  align-items: center;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.pageStyle {
  position: fixed;
  bottom: 22px;
  margin-left: 9vw;
}

/deep/ .el-card__body {
  padding: 12px;
}

.box-card {
  width: 350px;
  margin-bottom: 7px;
  margin-top: 7px;
  margin-left: 5%;
}

.header-right {
  text-align: right;
}

.content-item {
  padding: 10px 0;
}

.text {
  font-size: 18px;
  text-align: left;
  text-justify: inter-word;
  padding: 0;
}

.eBook {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}

.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
.fontStyle{
  white-space: nowrap;
 overflow: hidden;
  text-overflow: ellipsis;
}
</style>
